import React, { useEffect, useState } from "react"
import { Canvas, View } from "@tarojs/components"
import uCharts from '@qiun/ucharts';
import Taro from "@tarojs/taro";
import http from "@/request";
import moment from "moment";
import account from "@/store/account";
import categorys from "@/store/categorys";
import { MoneyFormat } from "@/utils/format";
import viewMode from "@/store/viewMode";
import "./index.scss"
import { VibrateShort } from "@/utils";

interface dataType {
    balance: number
    category: number
    date: string | null
    expense: number
    income: number
    month: string | null
    userId: number
}

let resData: dataType[] = []
let uChartsInstance: any = {};
const MonthPieChart: React.FC<{ month?: string, onSelect: (data: any) => void }> = ({ month, onSelect }) => {

    const [moneyType, setMoneyType] = useState('expense')
    const [categoryType, setCategoryType] = useState('category')
    const queryData = (categoryType) => {
        const day = moment(month)
        http.post(`/bills/statistics/${categoryType}`, {
            startDate: day.startOf('month').format('YYYY-MM-DD'),
            endDate: day.endOf('month').format('YYYY-MM-DD'),
            accountId: account.activeAccount?.id
        }).then(res => {
            resData = res.data
            drawCharts(categoryType, moneyType)
        })
    }

    const dataHandler = (categoryType, moneyType) => {
        // 成员或者消费类型
        const dataMap = categoryType === 'category' ? categorys.categoryMap : (account.activeAccount?.members || []).reduce((obj, user) => {
            const userId = user.userId as number
            return {
                ...obj,
                [userId]: user.userName
            }
        }, {})
        const sumVal = resData.reduce((sum, item) => {
            return sum + item[moneyType]
        }, 0)

        return resData.map(item => {
            return {
                value: item[moneyType],
                name: categoryType === 'category' ? dataMap[item.category]?.name || '' : dataMap[item.userId],
                itemId: categoryType === 'category' ? item.category : item.userId,
                categoryType,
                moneyType
            }
        })
            .filter(item => {
                return item.value / sumVal > 0.005
            })
    }

    Taro.useDidShow(() => {
        if (resData.length) {
            // drawCharts(categoryType, moneyType)
        }
    })

    useEffect(() => {
        if (month) {
            queryData(categoryType)
        }
    }, [month, categoryType])

    const drawCharts = (categoryType, moneyType) => {
        const sysInfo = Taro.getWindowInfo();
        let ctx = Taro.createCanvasContext('pie_id');
        uChartsInstance = new uCharts({
            type: "pie",
            context: ctx,
            width: 700 / 750 * sysInfo.screenWidth,
            height: 500 / 750 * sysInfo.screenWidth,
            fontColor: viewMode.isNight ? '#fff' : '#25283b',
            series: [
                {
                    data: dataHandler(categoryType, moneyType)
                }
            ],
            pixelRatio: 1,
            animation: true,
            background: "#FFFFFF",
            color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
            padding: [5, 5, 5, 5],
            enableScroll: false,
            legend: {
                fontColor: viewMode.isNight ? '#fff' : '#25283b',
                fontSize: 12
            },
            extra: {
                tooltip: {},
                pie: {
                    activeOpacity: 0.5,
                    activeRadius: 10,
                    offsetAngle: 0,
                    labelWidth: 15,
                    border: true,
                    borderWidth: 2,
                    borderColor: "#FFFFFF"
                }
            }
        });
    }

    const switchMoneyType = (type) => {
        VibrateShort()
        setMoneyType(type)
        drawCharts(categoryType, type)
        onSelect(undefined)
    }

    const switchCategoryTypeType = (type) => {
        VibrateShort()
        setCategoryType(type)
        queryData(type)
        onSelect(undefined)
    }
    const tap = (e) => {
        uChartsInstance.touchLegend(e);
        uChartsInstance.showToolTip(e, {
            // formatter: (item, category, index, opts) => {
            formatter: (item) => {
                onSelect(item)
                return `${item.name}：${MoneyFormat(item.value)}`;
            }
        });
    }

    return (<View className="month-chart-container card-background flex-column" key={account.accountIndex}>
        <View className="type-switch font-size28 flex-row flex-item text-main-color">
            <View onClick={() => switchCategoryTypeType('category')} className={`type-item ${categoryType === 'category' ? ' active' : ''}`}>
                <View className="type-name">分类</View>
                <View className="bottom-line bg-contrast-color"></View>
            </View>
            <View onClick={() => switchCategoryTypeType('member-cash')} className={`type-item ${categoryType === 'member-cash' ? ' active' : ''}`}>
                <View className="type-name">成员</View>
                <View className="bottom-line bg-contrast-color"></View>
            </View>
            <View onClick={() => switchMoneyType('expense')} className={`type-item ${moneyType === 'expense' ? ' active' : ''}`} style={{ marginLeft: '30rpx' }}>
                <View className="type-name">支出</View>
                <View className="bottom-line bg-contrast-color"></View>
            </View>
            <View onClick={() => switchMoneyType('income')} className={`type-item ${moneyType === 'income' ? ' active' : ''}`}>
                <View className="type-name">收入</View>
                <View className="bottom-line bg-contrast-color"></View>
            </View>
            <View className="flex1"></View>
            <View className="chart-title right-content">{moment(month).format('YYYY年MM月')}</View>
        </View>
        <Canvas
            canvas-id="pie_id"
            id="pie_id"
            className="pie-chart"
            onClick={tap} />
        <View className="tips font-size20 text-main-color">注：占比小于0.5%的类别，饼图中不会展示，点击查看分类前五</View>
    </View>)
}

export default MonthPieChart